package org.jsola.hr.web;

import org.apache.commons.lang3.StringUtils;
import com.alibaba.excel.util.CollectionUtils;
import org.jsola.contract.vo.ContractCountVO;
import org.jsola.core.Page;
import org.jsola.core.Result;
import org.jsola.exception.ParamException;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dto.MemoInfoAddDTO;
import org.jsola.hr.dto.MemoInfoBatchDTO;
import org.jsola.hr.dto.MemoInfoUpdateDTO;
import org.jsola.hr.provider.IContractProviderService;
import org.jsola.hr.query.MemoInfoQuery;
import org.jsola.hr.service.IMemoConfigService;
import org.jsola.hr.service.IMemoInfoService;
import org.jsola.hr.vo.*;
import org.jsola.user.core.TokenUser;
import org.jsola.user.core.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;


/**
 * 备忘录
 *
 * @author zhr
 */
@RestController("hrMemoInfoController")
@RequestMapping(HrConstants.API_PATH + "/v1/memoInfos")
public class MemoInfoController implements IMemoInfoControllerAPI {

    @Autowired
    private IMemoInfoService memoInfoService;

    @Autowired
    private IContractProviderService contractProviderService;

    @Autowired
    private IMemoConfigService memoConfigService;

    @Override
    @PostMapping
    public Result<MemoInfoVO> save(@Valid @RequestBody MemoInfoAddDTO memoInfoAddDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 新增备忘录权限校验

        return Result.success(
                memoInfoService.save(memoInfoAddDTO, tokenUser)
        );
    }


    @Override
    @PutMapping
    public Result<Integer> update(@Valid @RequestBody MemoInfoUpdateDTO memoInfoUpdateDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 修改备忘录权限校验

        int count = memoInfoService.update(memoInfoUpdateDTO, tokenUser);

        //判断是不是定期备忘，如果是，批量更新全部
        memoConfigService.updateByMemoId(memoInfoUpdateDTO, tokenUser);

        if (count == 0) {
            throw new ParamException("更新失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @PutMapping("/completed")
    public Result<Integer> completed(@Valid @RequestBody MemoInfoUpdateDTO memoInfoUpdateDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 修改备忘录权限校验

        int count = memoInfoService.update(memoInfoUpdateDTO, tokenUser);

        if (count == 0) {
            throw new ParamException("更新失败，请刷新页面后重试");
        }
        return Result.success(count);
    }


    @Override
    @PostMapping(value = "/batch")
    public Result batch(@Valid @RequestBody MemoInfoBatchDTO memoInfoBatchDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 批量操作权限校验

        // 批量操作，注意校验，有越权风险
        // 新增
        List<MemoInfoAddDTO> memoInfoAddDTOList = memoInfoBatchDTO.getMemoInfoAddDTOList();
        if (!CollectionUtils.isEmpty(memoInfoAddDTOList)) {
            memoInfoService.batchSave(memoInfoAddDTOList,tokenUser);
        }
        // 修改
        List<MemoInfoUpdateDTO> memoInfoUpdateDTOList = memoInfoBatchDTO.getMemoInfoUpdateDTOList();
        if (!CollectionUtils.isEmpty(memoInfoUpdateDTOList)) {
            memoInfoUpdateDTOList.parallelStream().forEach(
                    memoInfoUpdateDTO -> {
                        memoInfoService.update(memoInfoUpdateDTO,tokenUser);
                    }
            );
        }
        // 删除
        List<String> deleteMemoInfoIdList = memoInfoBatchDTO.getDeleteMemoInfoIdList();
        if (!CollectionUtils.isEmpty(deleteMemoInfoIdList)) {
            memoInfoService.deleteByIds(tokenUser,deleteMemoInfoIdList.toArray(new String[0]));
        }
        return Result.success();
    }


    @Override
    @DeleteMapping(value = "/{memoInfoId}")
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public Result<Integer> delete(@PathVariable String memoInfoId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 彻底删除备忘录权限校验

        //先删除备忘录配置
        memoConfigService.deleteByMemoId(memoInfoId, tokenUser);

        memoInfoService.deleteByIds(tokenUser, memoInfoId);

        return Result.success();
    }

    @Override
    @DeleteMapping
    public Result<Integer> deleteBatch(@RequestBody String[] memoInfoIds) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 批量彻底删除备忘录权限校验

//        int count = memoInfoService.deleteByIds(tokenUser, memoInfoIds);
//        if (count == 0) {
//            throw new ParamException("删除失败，请刷新页面后重试");
//        }
//        return Result.success(count);
        for (String memoInfoId : memoInfoIds) {
            memoConfigService.deleteByMemoId(memoInfoId, tokenUser);
            memoInfoService.deleteByIds(tokenUser, memoInfoId);
        }

        return Result.success();

    }

    @Override
    @GetMapping(value = "/{memoInfoId}")
    public Result<MemoInfoVO> findById(@PathVariable String memoInfoId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看备忘录权限校验

        MemoInfoVO memoInfoVO = memoInfoService.selectById(memoInfoId, tokenUser.getSiteId());
        //旧数据没有备忘录配置
        String configId = memoInfoVO.getConfigId();
        if (StringUtils.isNotBlank(configId)) {
            MemoConfigVO memoConfigVO = memoConfigService.selectById(configId, tokenUser.getSiteId());
            memoInfoVO.setRemindType(memoConfigVO.getRemindType());
            memoInfoVO.setRemindUnit(memoConfigVO.getRemindUnit());
            memoInfoVO.setRemindMonthUnitValue(memoConfigVO.getRemindMonthUnitValue());
        } else {
            memoInfoVO.setRemindType(1);
        }

        return Result.success(
                memoInfoVO
        );
    }

    @Override
    @GetMapping(value = "/listAll")
    public Result<List<MemoInfoListVO>> listAll(@Valid MemoInfoQuery memoInfoQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看备忘录权限校验

        return Result.success(
            memoInfoService.select(memoInfoQuery, tokenUser.getSiteId())
        );
    }


    @Override
    @GetMapping
    public Result<Page<MemoInfoListVO>> page(@Valid MemoInfoQuery memoInfoQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
            memoInfoService.selectPage(memoInfoQuery, tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping(value = "/getHomePageMemoRemindRelation")
    public Result<HomePageMemoRemindRelationVO> getHomePageMemoRemindRelation(@Valid MemoInfoQuery memoInfoQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看备忘录权限校验

        return Result.success(
                memoInfoService.getHomePageMemoRemindRelation(memoInfoQuery, tokenUser)
        );
    }

    @Override
    @GetMapping(value = "/getContractCount")
    public Result<ContractCountVO> getContractCount(Integer contractType, String subjectId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看备忘录权限校验

        return Result.success(
                contractProviderService.getContractCount(contractType, subjectId, tokenUser)
        );
    }

    @Override
    @GetMapping(value = "/getMemoRemindListToday")
    public Result<HomePageMemoRemindRelationVO> getMemoRemindListToday(@Valid MemoInfoQuery memoInfoQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看备忘录权限校验

        return Result.success(
                memoInfoService.getMemoRemindListToday(memoInfoQuery, tokenUser)
        );
    }

    @Override
    @GetMapping(value = "/getCurrentUserNoticeList")
    public Result<HomePageMemoRemindRelationVO> getCurrentUserNoticeList(@Valid MemoInfoQuery memoInfoQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看备忘录权限校验

        return Result.success(
                memoInfoService.getCurrentUserNoticeList(memoInfoQuery, tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping(value = "/getToDoMemo")
    public Result<List<MemoListVO>> getToDoMemo(@RequestParam("yearly") Integer yearly,
                                                @RequestParam("monthly") Integer monthly,
                                                @RequestParam(value = "companyId",required = false) String companyId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看备忘录权限校验
        return Result.success(
                memoInfoService.getCompleteMemoListByYearlyAndMonthly(yearly, monthly, companyId, tokenUser)
        );
    }


}

